/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   14-7-29 下午2:42 Created by dwzhang
 */
package com.jade.framework.base.comm.netty;

import com.jade.framework.base.comm.CommEndpoint;
import com.jade.framework.base.comm.MessageCodec;
import com.jade.framework.base.comm.ProtocolSession;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 先写到ByteBuf中，直接利用Netty的ByteBuf，有一定的依赖，但是更加方便一些。
 *
 * @author dwzhang
 * @version 1.0 14-7-29 下午2:42
 */
public class NettyMessageEncoder extends MessageToByteEncoder
{
    protected CommEndpoint<Channel> endpoint;

    public NettyMessageEncoder(CommEndpoint<Channel> endpoint)
    {
        this.endpoint = endpoint;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object o, ByteBuf byteBuf)
            throws Exception
    {
        ProtocolSession session = endpoint.getSession(ctx.channel());
        MessageCodec<ByteBuf, ByteBuf> codec = session.getProtocol().getMessageCodec();
        codec.encode(session, byteBuf, o);
        session.getProtocol().getLog().trace("Send a message:" + o);
    }
}
